package com.xqnode.boot.controller;

import cn.hutool.crypto.SecureUtil;
import com.xqnode.boot.common.JsonResult;
import com.xqnode.boot.dao.UserMapper;
import com.xqnode.boot.model.User;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;

/**
 * created by xiaqing on 2019/3/6 20:11
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    /**
     * 查询所有用户
     *
     * @return
     */
    @GetMapping("/all")
    public JsonResult findAll() {
        return JsonResult.dataResult(userMapper.selectAll());
    }

    @PostMapping("/login")
    public JsonResult login(@RequestBody User user) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
        User result = userMapper.selectOne(user);
        if (result != null) {
            return JsonResult.dataResult("登录成功");
        }
        return JsonResult.errorResult("登录失败");
    }

    /**
     * 注册新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/registry")
    public JsonResult registry(@RequestBody User user) {
        String pwdMd5 = SecureUtil.md5(user.getPassword());
        user.setPassword(pwdMd5);
        user.setCreateTime(new Date());
        int count = userMapper.insertSelective(user);
        if (count > 0) {
            return JsonResult.dataResult(user);
        }
        return JsonResult.errorResult("注册失败");
    }

    /**
     * 根据登录名修改密码
     *
     * @param user
     * @return
     */
    @PutMapping("/changePwd")
    public JsonResult changePwd(@RequestBody User user) {
        String password = user.getPassword();
        String pwdMd5 = SecureUtil.md5(password);
        user.setPassword(pwdMd5);
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("loginName", user.getLoginName());
        int count = userMapper.updateByExampleSelective(user, example);
        if (count > 0) {
            return JsonResult.defaultResult();
        }
        return JsonResult.errorResult("修改密码失败");
    }


}
